<template>
  <div>
    <el-dialog v-model="dialogVisible" title="剪切板" width="800" draggable :fullscreen="false" :show-close="false">
      <div class="scrollable-area" ref="scrollableArea"> 
        <el-input v-model="textarea" type="textarea" :rows="2" placeholder="请输入内容" @keyup.enter="updateLocalStorage" @blur="updateLocalStorage" ></el-input>
        <div v-for="(text, index) in textareas" :key="index" class="readonly-textarea" >
          <el-input v-model="textareas[index]" type="textarea" readonly placeholder="点击复制内容" @click="copyText(textareas[index])" ></el-input>
          <el-button type="danger" icon="el-icon-delete" circle @click="deleteTextarea(index)" ></el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

const dialogVisible = ref(true);
const textareas = ref(JSON.parse(localStorage.getItem('copy')) || ['']);
const textarea = ref('');
const maxTextareas = 500;

const updateLocalStorage = () => {
  if(textarea.value){
    localStorage.setItem('copy', JSON.stringify([textarea.value,...textareas.value]));
    textareas.value = JSON.parse(localStorage.getItem('copy'))
    textarea.value = '';
  }
};

const copyText = (text) => {
  navigator.clipboard.writeText(text);
  ElMessage.success('内容已复制到剪贴板');
};

const deleteTextarea = (index) => {
  if (textareas.value.length > 1 && index < textareas.value.length) {
    textareas.value.splice(index, 1);
    updateLocalStorage();
    ElMessage.success('文本已删除');
  }
};
 
</script>

<style scoped>
.scrollable-area {
  max-height: 800px;
  overflow-y: auto;
}

.readonly-textarea {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.readonly-textarea .el-input {
  flex: 1;
}

.readonly-textarea .el-button {
  margin-left: 10px;
}
</style>